namespace Bt.Mvc
{
    using System;
    using Microsoft.SPOT;

    public class FillableViewResult
        : ViewResult
    {

        private FillableViewResult Layout { get; set; }
        public string LogFile;

        public override string RenderBody() 
        {
            string body = string.Empty;
            if (this.Layout != null)
            {
                body = this.Layout.RenderBody();
                this.Body = this.GetTemplateData(body);
                return this.GetData(this.Body);
            }
            
            this.Body = this.GetTemplateData(this.Body);
            return this.GetData(this.Body); 
        }

        private string GetTemplateData(string template)
        {
            string result = template;
            var start = template.IndexOf('{', 0);
            if (start > 0)
            {
                var end = template.IndexOf('}', start);
                var key = template.Substring(start+1, end - start-1);

                var val = this.GetKeyValue(key);

                if (val != null)
                {
                    result = template.Substring(0, start - 1) + val + this.GetTemplateData(template.Substring(end + 1, template.Length - end - 1));
                }
            }

            return result;
        }

        private string GetData(string template)
        {
            string result = template;
            var start = template.IndexOf('{', 0);
            if (start > 0) 
            { 
                var end = template.IndexOf('}', start);
                var key = template.Substring(start+1, end - start-1);
            
                var val = this.GetViewDataValue(key);
            
                if (val != null)
                {
                    result = template.Substring(0, start) + val + this.GetData(template.Substring(end + 1, template.Length - end - 1));
                }
            }
            return result;
        }

        private string GetKeyValue(string key)
        {
            foreach (var item in this.GetType().GetFields())
            {
                if (item.Name == key)
                {
                    var val = (string)item.GetValue(this);
                    return val;
                }
            }
 
            return string.Empty;
        }

        private string GetViewDataValue(string key)
        {
            if (this.ViewData != null) 
            { 
                foreach (var item in this.ViewData.GetType().GetFields())
                {
                    if (item.Name == key)
                    {
                        var val = (string)item.GetValue(this);
                        return val;
                    }
                }
            }
            return null;
        }
    }
}